import React, { useState, useEffect } from "react";
import { Tooltip } from "antd";
import { FullscreenOutlined, FullscreenExitOutlined } from "@ant-design/icons";

const getFullscreenElement = () =>
  document.fullscreenElement ||
  // @ts-ignore
  document.webkitFullscreenElement ||
  // @ts-ignore
  document.mozFullScreenElement ||
  // @ts-ignore
  document.msFullscreenElement;

const requestFullscreen = (el: HTMLElement) => {
  if (el.requestFullscreen) return el.requestFullscreen();
  // @ts-ignore
  if (el.webkitRequestFullscreen) return el.webkitRequestFullscreen();
  // @ts-ignore
  if (el.mozRequestFullScreen) return el.mozRequestFullScreen();
  // @ts-ignore
  if (el.msRequestFullscreen) return el.msRequestFullscreen();
};
const exitFullscreen = () => {
  if (document.exitFullscreen) return document.exitFullscreen();
  // @ts-ignore
  if (document.webkitExitFullscreen) return document.webkitExitFullscreen();
  // @ts-ignore
  if (document.mozCancelFullScreen) return document.mozCancelFullScreen();
  // @ts-ignore
  if (document.msExitFullscreen) return document.msExitFullscreen();
};

const FullscreenToggle: React.FC = () => {
  const [isFullscreen, setIsFullscreen] = useState(false);

  const handleToggle = () => {
    if (!isFullscreen) {
      requestFullscreen(document.documentElement);
    } else {
      exitFullscreen();
    }
  };

  useEffect(() => {
    const handler = () => setIsFullscreen(!!getFullscreenElement());
    document.addEventListener("fullscreenchange", handler);
    document.addEventListener("webkitfullscreenchange", handler);
    document.addEventListener("mozfullscreenchange", handler);
    document.addEventListener("MSFullscreenChange", handler);
    return () => {
      document.removeEventListener("fullscreenchange", handler);
      document.removeEventListener("webkitfullscreenchange", handler);
      document.removeEventListener("mozfullscreenchange", handler);
      document.removeEventListener("MSFullscreenChange", handler);
    };
  }, []);

  return (
    <Tooltip title={isFullscreen ? "退出全屏" : "全屏"}>
      <span
        style={{ fontSize: 18, marginRight: 16, cursor: "pointer" }}
        onClick={handleToggle}
      >
        {isFullscreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
      </span>
    </Tooltip>
  );
};

export default FullscreenToggle;
